package com.iye.puretennis.fragment;

import android.content.Context;
import android.content.Intent;
import android.view.*;
import android.widget.*;
import com.iye.puretennis.R;
import com.iye.puretennis.activity.CreateGroupActivity;
import com.iye.puretennis.custom.HuaWenHuPoEditText;
import com.iye.puretennis.custom.HuaWenHuPoTextView;
import com.iye.puretennis.domain.UrlSuffix;
import com.iye.puretennis.domain.UserToken;
import com.iye.puretennis.helper.*;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: jing wu
 * Date: 2014/11/26
 * Time: 10:32
 */
public class SearchGroupFragment extends TabFragment {

    public static final String TAG = "search_group";

    private HuaWenHuPoEditText searchGroupView;

    private List<Group> groups = new ArrayList<Group>();

    private GroupsAdapter groupsAdapter;

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public int getViewId() {
        return R.layout.searchgroup;
    }

    @Override
    public int getSourceId() {
        return R.id.search_group;
    }


    @Override
    public void onCustomCreateView(LayoutInflater inflater) {
        ImageButton addButton = (ImageButton) mainView.findViewById(R.id.group_add);

        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(fragmentActivity, CreateGroupActivity.class);
                startActivity(intent);
                fragmentActivity.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
            }
        });

        groupsAdapter = new GroupsAdapter(getActivity());

        searchGroupView = (HuaWenHuPoEditText) mainView.findViewById(R.id.search_group_view);

        searchGroupView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    if (i == KeyEvent.KEYCODE_ENTER) {
                        updateUI();
                    }
                }
                return false;
            }
        });

        ListView groupsView = (ListView) mainView.findViewById(R.id.group_list_view);

        groupsView.setAdapter(groupsAdapter);

        ImageButton searchGroupButton = (ImageButton) mainView.findViewById(R.id.search_btn);

        searchGroupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateUI();
            }
        });

        ImageButton cancelSearchButton = (ImageButton) mainView.findViewById(R.id.search_cancel_btn);

        cancelSearchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchGroupView.setText("");
                updateUI();
            }
        });

    }


    public void updateUI() {
        searchGroups();
    }

    private void searchGroups() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                UserToken userToken = dbManager.retrieveCurrentUser();
                JSONObject paramJson = new JSONObject();

                try {
                    String keyword = searchGroupView.getText().toString();

                    paramJson.put("keyword", keyword);
                    StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);

                    String jsonStr = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.GROUP_SEARCH), userToken.getToken(), paramEntity);

                    JSONObject groupsJson = new JSONObject(jsonStr);
                    JSONArray groupsArrays = groupsJson.getJSONArray("groups");
                    groups.clear();
                    for (int i = 0; i < groupsArrays.length(); i++) {
                        JSONObject groupJson = groupsArrays.getJSONObject(i);
                        String groupGuid = groupJson.getString("groupGuid");
                        String groupName = groupJson.getString("groupName");
                        boolean owner = groupJson.getBoolean("owner");
                        int participantsAmount = groupJson.getInt("participantsAmount");
                        groups.add(new Group(groupGuid, groupName, participantsAmount, owner));
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            groupsAdapter.notifyDataSetChanged();
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }


    class GroupsAdapter extends BaseAdapter implements Filterable {

        public Context context;


        public List<Group> orig;

        public GroupsAdapter(Context context) {
            this.context = context;
        }

        public class GroupHolder {

            public HuaWenHuPoTextView nameView;

            public HuaWenHuPoTextView participantsAmountView;

            public GroupHolder(HuaWenHuPoTextView nameView, HuaWenHuPoTextView participantsAmountView) {
                this.nameView = nameView;
                this.participantsAmountView = participantsAmountView;
            }
        }


        @Override
        public int getCount() {
            return groups.size();
        }

        @Override
        public Object getItem(int position) {
            return groups.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }


        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            GroupHolder holder;
            HuaWenHuPoTextView nameView, amountView;

            if (convertView == null) {//为第一页显示,创建view对象
                convertView = LayoutInflater.from(context).inflate(R.layout.searchgroup_item, null);//null没有根元素
                nameView = (HuaWenHuPoTextView) convertView.findViewById(R.id.group_name);
                amountView = (HuaWenHuPoTextView) convertView.findViewById(R.id.group_p_amount);

                holder = new GroupHolder(nameView, amountView);
                convertView.setTag(holder);
            } else {
                holder = (GroupHolder) convertView.getTag();
                nameView = holder.nameView;
                amountView = holder.participantsAmountView;
            }

            final Group group = groups.get(position);
            nameView.setText(group.name);
            amountView.setText(group.participantsAmount + " " + getResources().getString(R.string.ren));

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Session session = Session.newSession();
                    session.put("groupGuid", group.guid);
                    goFragment(R.id.search_group, MyJoinedGroupFragment.TAG, MyJoinedGroupFragment.class, null, false);
                }
            });
            convertView.setOnLongClickListener(new View.OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {

                    showPopupMenu(v, R.menu.details_join_menu, new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem item) {

                            sendInvitation(group.guid);

                            return true;
                        }
                    });

                    return true;
                }
            });
            return convertView;
        }


        public Filter getFilter() {
            return new Filter() {

                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    final FilterResults oReturn = new FilterResults();
                    final ArrayList<Group> results = new ArrayList<Group>();
                    if (orig == null)
                        orig = groups;
                    if (constraint != null) {
                        if (orig != null && orig.size() > 0) {
                            for (final Group g : orig) {
                                if (g.name.toLowerCase()
                                        .contains(constraint.toString()))
                                    results.add(g);
                            }
                        }
                        oReturn.values = results;
                    }
                    return oReturn;
                }

                @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence constraint,
                                              FilterResults results) {
                    groups = (ArrayList<Group>) results.values;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            notifyDataSetChanged();
                        }
                    });
                }
            };
        }


    }

    private class Group {

        private String guid;

        private String name;

        private boolean owner;

        private int participantsAmount;


        public Group(String guid, String name, int participantsAmount, boolean owner) {
            this.guid = guid;
            this.name = name;
            this.participantsAmount = participantsAmount;
            this.owner = owner;
        }
    }


    private void sendInvitation(final String groupGuid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject paramJson = new JSONObject();
                try {
                    paramJson.put("guid", groupGuid);
                    StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);
                    String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.GROUP_JOINREQUEST_REQUEST), token.getToken(), paramEntity);
                    if (!Constant.RESPONSE_BADLY.equals(result)) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), getString(R.string.join_request_send), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


}
